<template>
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { reqImportEmployee } from '@/api/employee'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    handleSuccess({ header, results }) {
      if (this.type === 'user') {
        this.batchUser(header, results)
      }
      // if (this.type === 'salary') {
      //   this.batchSalary()
      // }
    },

    async batchUser(header, results) {
      //   console.log(header, results)

      //   result = [{入职时期:43535,姓名:jack,....},{}]
      //   data = [{timeOfEntry:43535,name:jack},{}]
      //   数据转换: 中文键 改成 英文键
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }

      const arr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
          const enkey = userRelations[k]

          if (['timeOfEntry', 'correctionTime'].includes(enkey)) {
            obj[enkey] = this.formatExcelDate(item[k])
          } else {
            obj[enkey] = item[k]
          }
        }
        arr.push(obj)
      })

      //   excel: 2019/3/11    43535   js读取excel不是以前理解时间戳
      //   js时间戳: 1970/1/1到 时间点  经过了多少毫秒
      //   js读取excel:   1900/1/1 到 时间点 经过了多少天

      //  批量添加员工
      await reqImportEmployee(arr)

      this.$message.success('批量添加员工成功')

      // 回退到上一个组件页面
      this.$router.back()

      // history:  history.go()  forward()  back()
    },

    // batchSalary() {
    //   ...
    // },

    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
